//record whole object,object must implements Serializable

import java.io.*;
import java.util.*;

public class Main{
	public static void main(String[] args){
		Member[] members={	new Member("JJ",90),
					new Member("kk",80),
					new Member("GG",70),};

		writeObjectToFile(members,args[0]);

		try{
			members=readObjectFromFile(args[0]);

			for(Member member:members){
				System.out.printf("%s=%d%n",member.getName(),member.getAge());
			}
			System.out.println();

			members=new Member[3];

			members[0]=new Member("baboo",55);
			members[1]=new Member("wan",30);
			appendObjectsToFile(members,args[0]);

			members=readObjectFromFile(args[0]);

			for(Member member:members){
				if(member!=null)//avoid null at last
					System.out.printf("%s=%d%n",member.getName(),member.getAge());
//				System.out.println(member);
			}


//			for(int i=0;i<6;i++){
//				System.out.printf("%s=%d%n",members[i].getName(),members[i].getAge());
//			}
		}
		catch(ArrayIndexOutOfBoundsException e){
			e.printStackTrace();
		}
		catch(FileNotFoundException e){
			e.printStackTrace();
		}


	}


	public static void writeObjectToFile(Object[] objs,String filename){
		File file=new File(filename);
		try{
			ObjectOutputStream objoutputstream=new ObjectOutputStream(new FileOutputStream(file));
			for(Object obj:objs){
				objoutputstream.writeObject(obj);
			}
			objoutputstream.close();
		}
		catch(IOException e){
			System.out.println("write");
			e.printStackTrace();
		}
	}


	public static Member[] readObjectFromFile(String filename)throws FileNotFoundException{
		File file=new File(filename);
		if(!file.exists()){
			throw new FileNotFoundException();
		}
		List<Member> list=new ArrayList<Member>();

		try{
			FileInputStream fileinputstream=new FileInputStream(file);

			ObjectInputStream objinputstream=new ObjectInputStream(fileinputstream);

			while(fileinputstream.available()>0){
				list.add((Member)objinputstream.readObject());
			}

			objinputstream.close();
		}
		catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		catch(IOException e){
			System.out.println("read");
			e.printStackTrace();
		}


		Member[] members=new Member[list.size()];
		return list.toArray(members);
	}


	public static void appendObjectsToFile(Object[] objs,String filename)throws FileNotFoundException{
		File file=new File(filename);
		if(!file.exists()){
			throw new FileNotFoundException();
		}
		try{
			ObjectOutputStream objoutputstream=new ObjectOutputStream(new FileOutputStream(file,true)){
				protected void writeStreamHeader() throws IOException{};
			};

			for(Object obj:objs){
				objoutputstream.writeObject(obj);
			}
			objoutputstream.close();

		}
		catch(IOException e){
			System.out.println("append");
			e.printStackTrace();
		}

	}
}